import SearchTop from "../../components/newSearchTop.vue";
import SearchTitle from "../../components/newSearchTitle.vue";
import slider from "../../components/sliders.vue";
import getGame from '@/api/getSearch'
import getMore from '@/api/more'
import getAwardDetail from '@/api/award/award-add'
import { jsCallNative } from "../../common/callnative"
import axios from 'axios';
import reportEvent from "../../components/report.js"
import $store from "../../components/vuex.js"
import Footer from "../../components/footer.vue"
import bindPhone from "../../components/bindPhone.vue"

export default {
    components: {
        SearchTop: SearchTop,
        slider: slider,
        bindPhone: bindPhone,
        Footer: Footer,
    },
    data() {
        return {
            gameType: [],
            banners: ["https://app.caizhanbao.cn/detault/6.png", "https://app.caizhanbao.cn/detault/6.png", "https://app.caizhanbao.cn/detault/6.png", "https://app.caizhanbao.cn/detault/6.png"],
            list: [],
            page: 1,
            listGame: [],
            gameCategory1: [],
            gameCategory2: [],
            category1: '',
            category2: '',
            subCategoryIndex: 0,
            categoryIndex: 0,
            channelInfo: {}, // 频道ID
            listId: 29147,
            //分页
            current: 1,
            showItem: 5,
            allpage: "",
            flag: true,
            token: window.sessionStorage.getItem("token"),
            //进入游戏接口
            gameurl: "http://pitf.vgs.lenovo.com.cn",
            softid: "",
            gameArr: [], // 二级数组用来存放分页的数据
            dataArr: [],
            gotoInput: 1,
            noPage: true,
            lenovoId: window.sessionStorage.getItem("lenovoId"),
            startTime: +new Date(),
            newService: '',
        }
    },

    mounted() {
        this.getGameLists()
        this.getGameTitle()
        if (typeof this.$route.query.errorMessage != "undefined" && this.$route.query.errorMessage != "") {
            this.$toast.center("错误")
        };

        reportEvent.pageIn(this.lenovoId, "103")
    },

    beforeDestroy() {
        reportEvent.pageOut(this.lenovoId, this.startTime, "103")

    },

    created() {
        //防止页面后退
        //处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外 
        function banBackSpace(e) {
            var ev = e || window.event; //获取event对象 
            var obj = ev.target || ev.srcElement; //获取事件源 

            var t = obj.type || obj.getAttribute('type'); //获取事件源类型 

            //获取作为判断条件的事件类型 
            var vReadOnly = obj.getAttribute('readonly');
            var vEnabled = obj.getAttribute('enabled');
            //处理null值情况 
            vReadOnly = (vReadOnly == null) ? false : vReadOnly;
            vEnabled = (vEnabled == null) ? true : vEnabled;

            //当敲Backspace键时，事件源类型为密码或单行、多行文本的， 
            //并且readonly属性为true或enabled属性为false的，则退格键失效 
            var flag1 = (ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") &&
                (vReadOnly == true || vEnabled != true)) ? true : false;

            //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效 
            var flag2 = (ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea") ?
                true : false;

            //判断 
            if (flag2) {
                return false;
            }
            if (flag1) {
                return false;
            }
        }

        //禁止后退键 作用于Firefox、Opera 
        document.onkeypress = banBackSpace;
        //禁止后退键 作用于IE、Chrome 
        document.onkeydown = banBackSpace;

    },

    computed: {
        pages: {
            get: function() {
                var pag = [];
                if (this.current < this.showItem) { //如果当前的激活的项 小于要显示的条数
                    //总页数和要显示的条数那个大就显示多少条
                    var i = Math.min(this.showItem, this.allpage);
                    while (i) {
                        pag.unshift(i--);
                    }
                } else { //当前页数大于显示页数了
                    var middle = this.current - Math.floor(this.showItem / 2), //从哪里开始
                        i = this.showItem;
                    if (middle > (this.allpage - this.showItem)) {
                        middle = (this.allpage - this.showItem) + 1
                    }
                    while (i--) {
                        pag.push(middle++);
                    }
                }

                return pag
            },
            set: function(newValue) { //如果不写计算属性的set，vue会报错


            }
        }
    },


    methods: {
        getGift() { // 领取礼包

            this.$router.push({ path: "../newGiftCenter/", query: {} })
        },
        //获得轮播图
        getGameLists() {
            getAwardDetail.getAwardDetail(104).then((res) => {
                console.log(res.data)
                $(window).scrollTop(0);
                // 轮播图
                this.banners = res.data.channels[0].modules[5].elements;

                this.banners.page = res.data.channels[0].channelName;
                this.banners.pageId = res.data.channels[0].id;
                // 频道信息
                this.channelInfo.id = res.data.channels[0].id;
                this.channelInfo.name = res.data.channels[0].channelName;
                console.log(this.banners)
                if (this.banners.length <= 1) {
                    $(".carousel-indicators").hide()
                }
                // console.log(this.goodGame)
            })
        },

        // 获取游戏列表
        async getGameTitle() {
            getGame.getMore().then((res) => {
                console.log(res)
                this.gameCategory1 = res.data.first
                this.gameCategory2 = res.data.second.slice(0, 5);
                let arr =[];
                this.gameCategory2.map(function(item,index){
                    if(item.cateName != "回合制" && item.cateName != "竞技"){
                        arr.push(item)
                    }
                })
                this.gameCategory2 = arr;


                this.category1 = this.gameCategory1[2].category1
                this.category2 = this.gameCategory2[0].category1
                this.getGame();

            });
        },

        // 点击游戏列表分类
        selectIndex(index, item, event) {

            let value = event.target.text
            $(".gameTitle a").removeClass("active")
            $(event.target).addClass("active")
            this.subCategoryIndex = index;
            this.category2 = item.category1;
            this.current = 1;
            this.page = 1;
            console.log(this.dataArr)
            let arr = []

            console.log(value)
            if (value == "全部") {
                arr = this.dataArr

            } else {
                for (var i in this.dataArr) {
                    if (this.dataArr[i].category2 == value) {
                        arr.push(this.dataArr[i])
                    }

                }
            }

            if (JSON.stringify(arr) === '[]') {
                this.flag = false;
                this.noPage = false;
            } else {
                this.flag = true;
                this.noPage = true;
                this.handleData(arr)
            }


            reportEvent.pageSelect(this.lenovoId)

        },
        handleData(data) {

            this.allpage = Math.ceil(data.length / 16)
            if (this.allpage <= 1) {
                this.noPage = false;
            }

            // 处理数据
            for (let j = 0; j < data.length; j++) {
                if (!data[j].captureFiles) {
                    data[j].bgUrl = ''
                } else {
                    for (let i = 0; i < data[j].captureFiles.length; i++) {
                        if (data[j].captureFiles[i].size == '270*210') {
                            data[j].bgUrl = data[j].captureFiles[i].url

                        }
                        // 获取游戏服务页面的图片
                        if (data[j].captureFiles[i].size == '270*600') {
                            data[j].serviceImg = data[j].captureFiles[i].url
                        }
                    }
                }
            }
            // 创建一个二维数组来放分组的数据
            for (var i = 0; i < this.allpage; i++) {
                let arr = []
                arr.push(data.slice(i * 16, (i + 1) * 16))
                this.gameArr[i] = arr
            }
            this.listGame = data.slice(0, 16); // 初始化数据
        },

        async getGame() {
            let that = this;
            let url = '/search/searchGame?relativeId=48&category1=0&category2=0&page=1'
            axios.get(url).then(function(res) {
                if (JSON.stringify(res.data.datas) === '[]') {
                    console.log(1)
                    that.flag = false;
                    that.noPage = false;
                    that.allpage = 0;
                } else {
                    that.flag = true;
                    that.noPage = true;
                    that.dataArr = res.data.datas

                    that.handleData(that.dataArr)
                }
            })
        },
        goDetails(Id, img, token) { // 选择服务器

            this.$router.push({ path: "../newService", query: { gameId: Id, imgUrl: img, token: token } })
        },
        //分页
        goto: function(index) {

            if (index == this.current) { // 点击当前页

                return false
            }
            if (/^[0-9]*$/.test(index) && index <= this.gameArr.length) {
                $(window).scrollTop(0)
                this.current = index;
                this.listGame = this.gameArr[index - 1][0]

            } else {
                this.$toast.center("请输入正确的数字")
                this.gotoInput = 1;
            }

        },
        pages: function() {
            var pag = [];
            if (this.current < this.showItem) { //如果当前的激活的项 小于要显示的条数
                //总页数和要显示的条数那个大就显示多少条
                var i = Math.min(this.showItem, this.allpage);
                while (i) {
                    pag.unshift(i--);
                }
            } else { //当前页数大于显示页数了
                var middle = this.current - Math.floor(this.showItem / 2), //从哪里开始
                    i = this.showItem;
                if (middle > (this.allpage - this.showItem)) {
                    middle = (this.allpage - this.showItem) + 1
                }
                while (i--) {
                    pag.push(middle++);
                }
            }
            return pag
        },
        
         //开始游戏
        gameStart(cpId,gameName,softId,serverId,serviceName) {//  cpId 游戏名称  softId   gameId  区服id，区服名
                let that = this;
                var url = `${this.gameurl}/gameRedirect/loginGame?cp=${cpId}_GAME&game=${softId}&gameName=${gameName}&token=${this.token}`

                this.saveGame(window.sessionStorage.getItem("lenovoId"),cpId,softId,48,serverId,serviceName,gameName)
                window.open(url)
                reportEvent.pageStartGame(this.userId)
        },
        saveGame(lenovoId,cpId,softId, relativeId, serverId,serviceName,gameName) { // 记录玩过的游戏 联想ID cpId softId  平台编号 区服id 区服名 游戏名
            let that = this;
            if (serverId && serviceName) {
                this.resSaveGame(lenovoId,cpId,softId, relativeId,softId, serverId,gameName,serviceName)
            } else {
                console.log(softId)
                let _url = this.gmConf.domainHttps+"unionlogin.4366.com/lenovo/gamecenter/gslist.do?jsonp&serverType=GENERAL&order=opentime:dasc&gsPageSize=5&online" + "&game=" + softId +"&gsPageNo=1"
                console.log(_url)
                that.jqajax(_url, { type: "post", dataType: "jsonp" },function(res){

                    var _servers = res[softId].servers;
                    var arr = []
                    for (var item in _servers) {
                        arr.push(_servers[item]);
                    }
                    
                    that.newService = arr[0]
                    console.log(that.newService)

                    that.resSaveGame(lenovoId,cpId,softId, relativeId, that.newService.id,that.newService.name,gameName)

                });
            }

        },
        resSaveGame(lenovoId,cpId,softId,relativeId,serverId,serviceName,gameName){
            let that =this
             let url = `/gift/api/webpagegame/collectionGame.do?lenovoId=${lenovoId}&relativeId=${relativeId}&serverId=${serverId}&softId=${softId}&serverName=${serviceName}&gameName=${gameName}&softName=${cpId}`;
                axios.get(url).then(function(res) {
                    if (res.data.code == 0) {
                        
                    } else {
                        that.$toast.center("请求错误")
                    }

                }, function(err) {

                })

        },


    }

}